const router = require('koa-router')()
const multer = require('koa-multer');//加载koa-multer模块  
const rimraf = require('rimraf')
const { spawn } = require('child_process');
const sqlService = require('../sqlServer');
const path = require('path');
const fs = require('fs');

const upload = multer({dest: 'public/'})
router.prefix('/users')


// -将回调转化为promise | 参数1：回调模式异步函数， 参数2：异步函数的参数， 返回值：[err, ...]数组
var makePromise = function (func, ...args) {
  return new Promise(function (resolve, reject) {
    var callback = function (...callArgs) {
      resolve(callArgs);
    }
    func(...args, callback);
  });
}
//-跨磁盘分区移动文件   | 参数1：文件名， 参数2：文件原路径， 参数3：文件新路径 
var save_file = async function (fileName, fileTmpPath, fileDirPath) {
  var err;
  // [err, result] = await makePromise(fs.readdir, fileDirPath)
  // console.log('err', err, 'result', result);
  [err] = await makePromise(fs.access, fileDirPath);
  if (err) {
    [err] = await makePromise(fs.mkdir, fileDirPath);
    if (err) {
      console.log('save_file - 创建文件夹失败');
    }
  }
  var fileNewPath = path.join(fileDirPath, fileName);
  var readStream  = fs.createReadStream(fileTmpPath);                            
  var writeStream = fs.createWriteStream(fileNewPath);
  readStream.pipe(writeStream); 
  readStream.on('end',async function(){
    [err] = await makePromise(fs.unlink, fileTmpPath);
    if (err) {
      console.log('save_file - unlink - err', err); 
    }                                               
  });
}
// -递归创建文件夹 | 参数：创建的路径
var my_mkdir = async function (dirPath) {
  var [err] = await makePromise(fs.mkdir, dirPath);
  console.log('dirPath', dirPath)
  if (err) {
    err = await my_mkdir(path.join(dirPath, '../.'));
    if(err){
      console.log('创建文件夹失败');
    }
    [err] = await makePromise(fs.mkdir, dirPath);
  }
  return 0;
}

// -上传文件
router.post('/', async (ctx, next) => {
  ctx.body = 'bu not Found';
  // - 文件名、文件类型、文件临时路径
  var { name: fileName, type: fileType, path: fileTmpPath } = ctx.request.body.files.file;
  var fileDirName = ctx.request.body.fields.name;                                       //-用户指定的存储文件夹名
  var fileDirPath     = path.join(__dirname, '../', '/public/uploads/', fileDirName);   //-文件存储文件夹的绝对路径
  var filterType  = ['image/pjpeg', 'image/jpeg', 'image/png', 'image/x-png'];          //-过滤的文件类型
  if(filterType.indexOf(fileType) === -1){
    console.log('只支持png和jpg格式图片')
    return -1;
  }
  save_file(fileName, fileTmpPath, fileDirPath);
})
// -执行图片转换
router.post('/bar', async function (ctx, next) {
  ctx.body = 'bu not Found'
  var err, result;
  var fileDirName = ctx.request.body.dirName;     //-房源的id编号
  var submitFiles = ctx.request.body.files;       //-确认提交的图片
  var fileOldPath = path.join(__dirname, '../public/uploads', fileDirName);           //-图片存储的中转路径
  var fileDirPath = path.join(__dirname, '../public/house_picture', fileDirName);     //-拼接房源全景图片存放的路径
  var krpanoPath  = 'F:\\3d全景图片\\krpano-1.19-pr14';                                //-全景处理程序绝对路径
  if(submitFiles.length <= 0 || fileDirName == ''){                           //-验证提交是否有效
    return -1;
  }
  var submitFileNames = submitFiles.map(item => {                             //-获取用户提交的文件名
    return item.name;
  })
  var [err] = await makePromise(fs.access, fileDirPath);                      //-判断该房源是否存在全景文件
  if(err) {                                                                   //-创建房源标号对应文件夹
    err = await my_mkdir(path.join(fileDirPath, 'photo'))
    if (err) { console.log('创建文件夹失败'); return -1; }
  }
  err = await moveFiles(fileOldPath, path.join(fileDirPath, 'photo'), submitFileNames);
  if (err) { console.log('移动文件错误'); return -1; }

  var fileNames, filePaths;
  [err, fileNames] = await makePromise(fs.readdir, path.join(fileDirPath, 'photo'));
  if (err) { console.log('readdir - 错误', err); return -1; }
  filePaths = fileNames.map(fileName => {                 //-取出所有图片路径
    return path.join(path.join(fileDirPath, 'photo'), fileName)
  })
  const bat = spawn('a.bat', filePaths, {cwd: path.join(krpanoPath)});
  bat.stdout.on('data', (data) => {
      console.log(data.toString());
  });
  bat.stderr.on('data', (data) => {
      console.log(data.toString());
  });
  bat.on('exit', async (code) => {
      console.log(`子进程退出码：${code}`);
      await afterConversion(ctx);
  });
})
// 将用户指定的图片移动到指定路径下,删除原文件夹
var moveFiles = async function (oldPath, newPath, fileNames) {
  for(let fileName of fileNames){
    let [err] = await makePromise(fs.rename, path.join(oldPath, fileName), path.join(newPath, fileName));
    if(err) { console.log('movePhoto - 重命名文件失败'); return -1; }
  }
  let [err] = await makePromise(rimraf, oldPath)
  if(err) { console.log('movePhoto - 删除文件夹失败'); return -1; }
  return 0;
}
// 打完包执行对3d全景文件的重命名和移动
var afterConversion = async function (ctx) {
  var fileDirName = ctx.request.body.dirName;
  var fileDirPath = path.join(__dirname, '../public/house_picture', fileDirName);
  var fileUrl = ctx.request.origin + '/' + fileDirName + '/vtour/tour.html'
  //- 图片处理前的路径， 图片处理后的存放路径
  var oldDirPath = path.join(fileDirPath, 'photo/vtour');
  var newDirPath = path.join(fileDirPath, 'vtour');
  var fileData;
  var [err] = await makePromise(fs.access, newDirPath);
  if(!err) {
    [err] = await makePromise(rimraf, newDirPath);
    if(err) { console.log('afterConversion - 删除文件夹失败'); return -1; } 
  }
  [err] = await makePromise(fs.rename, oldDirPath, newDirPath);
  if (err) { console.log('转存全景文件夹失败'); return -1;}
  [err, fileData] = await makePromise(fs.readFile, path.join(newDirPath, 'tour.xml'), { encoding: 'utf8'});
  if (err) { console.log('转存全景文件夹失败'); return -1;}
  fileData = fileData.replace('Virtual Tour', '千家房地产');  
  [err] = await makePromise(fs.writeFile, path.join(newDirPath, 'tour.xml'), fileData);
  if (err) { console.log('修改文件失败！'); return -1;}
  sqlService.addData(path.join(newDirPath, '../photo'), path.join(newDirPath, 'tour.html'));
  console.log('fileUrl', fileUrl)
  global.socket.emit('customEmit', { url: fileUrl })
}
module.exports = router
